package internal

import (
	"Redbook/redbook/internal/midderware"
	"Redbook/redbook/internal/reposetery"
	"Redbook/redbook/internal/reposetery/dao"
	"Redbook/redbook/internal/server"
	"Redbook/redbook/internal/web"
	iplimiter "github.com/Salvatore-Giordano/gin-redis-ip-limiter"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gormlogger "gorm.io/gorm/logger"
	"log"
	"net/http"
	"os"
	"time"
)

func Server() {
	logger, err := zap.NewDevelopment()
	if err != nil {
		panic(err)
	}

	cdb, bdb := Dataconon()
	serverc := gin.Default()
	serverc.Use(midderware.NewlogBuild(logger).Build(),
		iplimiter.NewRateLimiterMiddleware(redis.NewClient(&redis.Options{
			Addr:     "localhost:6379",
			Password: "",
			DB:       1,
		}), "general", 200, 60*time.Second),
	) //使用中间件
	serverc.LoadHTMLGlob("/Users/hucc1/Documents/gop/Redbook/redbook/template/*.gohtml")
	serverc.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusTemporaryRedirect, "/login")
	})

	cdao := dao.NewArticleDao(cdb) //线上库
	crepo := reposetery.NewRepo(cdao)

	bdao := dao.NewArticleDao(bdb) //提交库
	brepo := reposetery.NewRepo(bdao)

	Articleserver := server.NewArticleService(crepo, brepo)
	Articcontrol := web.ArticleContol{Articleserver}
	Articcontrol.RegistRouter(serverc)

	ldao := dao.NewLogindao(cdb)
	lrepo := reposetery.NewLogin(ldao)
	loginserver := server.NewLoginserver(lrepo)
	LoginControl := web.Logincontrol{loginserver}
	LoginControl.RegistRouter(serverc)
	serverc.Run(":8099")
}
func Dataconon() (cdb, bdb *gorm.DB) {
	dsn := "root:huchaoyyds@tcp(127.0.0.1:3306)/redb?charset=utf8mb4&parseTime=True&loc=Local"
	cdb, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: gormlogger.New(log.New(os.Stdout, "储存库", log.LstdFlags), gormlogger.Config{
			SlowThreshold:             100 * time.Millisecond, // Slow SQL threshold
			LogLevel:                  gormlogger.Warn,        // Log level
			IgnoreRecordNotFoundError: true,                   // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,                   // Don't include params in the SQL log
			Colorful:                  true,                   // Disable color
		}),
	})
	if err != nil {
		panic(err)
	}

	dsn2 := "root:huchaoyyds@tcp(127.0.0.1:3306)/rebp?charset=utf8mb4&parseTime=True&loc=Local"
	bdb, err = gorm.Open(mysql.Open(dsn2), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	return cdb, bdb
}
